import {
	defineStore
} from 'pinia';
import userApi from '@/sheep/api/user';
import $share from '@/sheep/platform/share';
import {
	isEmpty,
	cloneDeep,
	clone
} from 'lodash';

// 默认用户信息
const defaultUserInfo = {
	avatar: './../../static/empty/avatar.png', // 头像
	name: '游客', // 昵称
	phone: '', // 手机号
	roleType: 21, // 用户类型，默认为“试用用户”
};

const user = defineStore('user', {
	state: () => ({
		userInfo: clone(defaultUserInfo), // 用户信息
		isLogin: !!uni.getStorageSync('token') || false, // 登录状态
		authModal: false, //权限弹窗
	}),

	actions: {
		// 获取个人信息
		async getInfo() {
			const {
				error,
				data
			} = await userApi.profile();
			if (error !== 0) return;
			// 设置默认头像
			this.userInfo = Object.assign(data, {
				avatar: defaultUserInfo.avatar
			});
		},

		// 设置token
		setToken(token = '') {
			if (token === '') {
				this.isLogin = false;
				uni.removeStorageSync('token');
			} else {
				this.isLogin = true;
				uni.setStorageSync('token', token);
				this.loginAfter();
			}
			return this.isLogin;
		},

		// 更新用户相关信息 
		async updateUserData(data) {
			if (!this.isLogin) {
				this.resetUserData();
				return;
			}
			if (data) {
				this.userInfo = Object.assign(data, {
					avatar: defaultUserInfo.avatar,
				});
			} else {
				await this.getInfo();
			}
			return this.userInfo;
		},

		// 重置用户默认数据
		resetUserData() {
			console.log('重置用户信息了')
			this.setToken();
			this.userInfo = clone(defaultUserInfo);
		},

		// 登录后
		async loginAfter() {
			await this.updateUserData();
			// 登录后设置全局分享参数
			$share.getShareInfo();
		},

		// 登出
		async logout(boo = false) {
			if (boo) {
				const res = await userApi.logout();
				console.log('logout result is', res)
			}
			this.resetUserData();
		},
		// 设置权限弹窗
		setAuthModal(data = false) {
			this.authModal = data;
		}
	},
	persist: {
		pick: ['userInfo']
	},
});

export default user;